import { createMissionTemplate, getTemplatePathList, updateMissionTemplate } from '@/api'
import { ElMessage } from '@/stores/elMessage'
import type { TemplateData } from '@/types'
import { i18n } from '@/utils'
import { ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import { getLineCoordinates, havePath } from '.'
import { clearMenu } from './base'
import { clearDrawTool } from './drawTool'
import { clearPathLayer, pathPointsData } from './path'
import { clearPathToolbarEvent } from './patrolPath'
import { useRecordStore } from './record'

export interface FormData {
  name?: string
  memo?: string
  type?: number
}

//搜索模板列表

export let currentTemplate: TemplateData | null

export const setCurrentTemplate = (val: TemplateData | null) => {
  currentTemplate = val
}

export const initialParams = {
  limit: 10,
  page: 1,
  rtype: 'patroling',
  type: 1
}

export const queryFields = [
  {
    prop: 'name',
    title: i18n.global.t('ren-wu-ming-cheng')
  },
  {
    prop: 'memo',
    title: i18n.global.t('bei-zhu')
  }
]

export const params: Record<string, any> = ref(Object.assign({}, initialParams))

export const list = ref<any[]>([])
export const total = ref(0)

/**
 * 获取路线模板列表数据
 */
export async function getList() {
  const res = await getTemplatePathList(params.value)
  list.value = res.data.list || []
  total.value = res.data ? res.data.total : 0
}

/**
 * 保存模板的表单数据
 */
export const formData = ref<FormData>({ name: '', memo: '', type: 1 })

/**
 * 路线模板id
 */
export const missionTemplateId = ref<number | null | undefined>()

/**
 * 是否显示保存路线模板窗口
 */
export const templateDialogVisible = ref(false)
// 确定保存路线模板
export const handleConfirm = async (formList: { name?: string; memo?: string; type?: number }) => {
  const record = useRecordStore()
  const data = {
    id: missionTemplateId.value,
    mission: record.isRecordPath
      ? JSON.stringify(getLineCoordinates(record.recordPathPoints))
      : JSON.stringify(pathPointsData.value),
    name: formList.name,
    memo: formList.memo,
    rtype: 'patroling',
    type: formList.type
  }
  //更新已选的模板路线
  if (missionTemplateId.value) {
    const res: any = await updateMissionTemplate(data)
    ElMessage({
      type: 'success',
      message: res.message
    })
    missionTemplateId.value = undefined
  } else {
    //新增模板路线
    const res: any = await createMissionTemplate(data)
    ElMessage({
      type: 'success',
      message: res.message
    })
  }

  templateDialogVisible.value = false
  clearPathLayer()
  clearDrawTool()
  record.closeIsRecordPath()
  record.recordPathPoints.length = 0
  clearMenu()
}

export const closeTemplate = async () => {
  const record = useRecordStore()
  try {
    await ElMessageBox.confirm(
      i18n.global.t('que-ding-bu-bao-cun-lu-xian-ma'),
      i18n.global.t('ti-shi'),
      {
        confirmButtonText: i18n.global.t('que-ding'),
        cancelButtonText: i18n.global.t('qu-xiao'),
        type: 'warning'
      }
    )

    templateDialogVisible.value = false
    ElMessage({
      type: 'warning',
      message: i18n.global.t('yi-qu-xiao-bao-cun-lu-xian')
    })

    if (record.isRecordPath) {
      clearMenu()
      record.closeIsRecordPath()
      record.recordPathPoints.length = 0
    }
  } catch (error) {
    return error
  }
}

// 搜索模板弹窗是否可见
export const templateSearchDialogVisible = ref(false)

export const saveTemplateToolbarEvent = () => {
  const record = useRecordStore()
  if (havePath() && record.endRecording()) {
    clearDrawTool()
    clearPathToolbarEvent()
    templateDialogVisible.value = true
  }
}

export const searchTemplateToolbarEvent = () => {
  const record = useRecordStore()
  if (record.endRecording()) {
    clearDrawTool()
    clearPathToolbarEvent()
    templateSearchDialogVisible.value = true
  }
}
